/**
 * UniApp兼容的网络请求工具
 * 支持H5、App等所有UniApp平台
 */

// 获取API基础URL
function getBaseURL() {
  const baseURL = process.env.VUE_APP_BASE_API || 'http://192.168.124.24:8001/api';
  console.log('Environment Info:', {
    NODE_ENV: process.env.NODE_ENV,
    VUE_APP_BASE_API: process.env.VUE_APP_BASE_API,
    actualBaseURL: baseURL,
    currentTime: new Date().toLocaleString()
  });
  return baseURL;
}

/**
 * 统一的网络请求方法
 * @param {Object} options 请求配置
 * @returns {Promise} 请求结果
 */
export function request(options) {
  const baseURL = getBaseURL();
  const requestStartTime = Date.now();
  
  return new Promise((resolve, reject) => {
    const config = {
      url: baseURL + options.url,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      timeout: 10000,
      success: (res) => {
        console.log(`[${new Date().toISOString()}] API Success - ${config.method} ${config.url}:`, {
          status: res.statusCode,
          data: res.data,
          duration: Date.now() - requestStartTime
        });
        resolve(res);
      },
      fail: (err) => {
        const errorInfo = {
          timestamp: new Date().toISOString(),
          method: config.method,
          url: config.url,
          duration: Date.now() - requestStartTime,
          error: err
        };
        
        let userMessage = '';
        
        if (err.errMsg) {
          if (err.errMsg.includes('timeout')) {
            userMessage = '网络请求超时，请检查网络连接后重试';
            errorInfo.category = 'TIMEOUT';
          } else if (err.errMsg.includes('fail')) {
            userMessage = '网络连接失败，请检查网络设置';
            errorInfo.category = 'NETWORK_ERROR';
          } else if (err.errMsg.includes('abort')) {
            userMessage = '请求被中断，请重试';
            errorInfo.category = 'REQUEST_ABORTED';
          } else {
            userMessage = `请求失败: ${err.errMsg}`;
            errorInfo.category = 'UNKNOWN_ERROR';
          }
        } else {
          userMessage = '网络请求失败，请检查网络连接';
          errorInfo.category = 'NETWORK_ERROR';
        }
        
        console.error(`[${errorInfo.timestamp}] API Request Failed:`, errorInfo);
        
        err.userMessage = userMessage;
        err.errorInfo = errorInfo;
        reject(err);
      }
    };
    
    console.log('Sending request to:', config.url);
    uni.request(config);
  });
}

/**
 * GET请求
 * @param {string} url 请求路径
 * @param {Object} params 查询参数
 * @returns {Promise} 请求结果
 */
export function get(url, params) {
  let requestUrl = url;
  if (params) {
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&');
    requestUrl += '?' + queryString;
  }
  
  return request({
    url: requestUrl,
    method: 'GET'
  });
}

/**
 * POST请求
 * @param {string} url 请求路径
 * @param {Object} data 请求数据
 * @returns {Promise} 请求结果
 */
export function post(url, data) {
  return request({
    url: url,
    method: 'POST',
    data: data
  });
}

/**
 * PUT请求
 * @param {string} url 请求路径
 * @param {Object} data 请求数据
 * @returns {Promise} 请求结果
 */
export function put(url, data) {
  return request({
    url: url,
    method: 'PUT',
    data: data
  });
}

/**
 * DELETE请求
 * @param {string} url 请求路径
 * @returns {Promise} 请求结果
 */
export function del(url) {
  return request({
    url: url,
    method: 'DELETE'
  });
}

export default {
  request,
  get,
  post,
  put,
  del
};